<template>
  <div class="user-select">
    <el-tree-select
      v-model="selectedUsers"
      :data="userList"
      :props="{
        value: 'id',
        label: 'label',
        children: 'children'
      }"
      placeholder="请选择用户"
      multiple
      filterable
      check-strictly
      @change="handleTreeSelectChange"
    />
    <el-select
      v-model="priority"
      placeholder="请选择优先级"
      class="priority-select"
    >
      <el-option
        v-for="item in priorityOptions"
        :key="item.code"
        :label="item.value"
        :value="item.code"
      />
    </el-select>
    <div class="dialog-footer">
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { userTree } from '@/api/system/user';
import { getEnums } from '@/api/system/enums';
import { EnumType } from '@/api/system/enums.type';
const { proxy } = getCurrentInstance();

const emit = defineEmits(['confirm', 'cancel']);

const userList = ref([]);
const selectedUsers = ref([]);
const priority = ref('');
const priorityOptions = ref([]);

// 获取优先级枚举值
function getPriorityOptions() {
  getEnums(EnumType.MessagePriority).then(response => {
    priorityOptions.value = response.data;
  });
}

// 获取用户列表
function getUsers() {
    userTree().then(response => {
        userList.value = response.data;
    });
}

// 递归查找节点
function findNodeById(nodes, id) {
  for (const node of nodes) {
    if (node.id === id) {
      return node;
    }
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
}

// 递归获取部门下所有用户节点
function getAllUserNodes(node) {
  let userNodes = [];
  if (node.type === 'user') {
    userNodes.push(node.id);
  }
  if (node.children) {
    node.children.forEach(child => {
      userNodes = userNodes.concat(getAllUserNodes(child));
    });
  }
  return userNodes;
}

// 检查部门下用户节点的选中状态
function checkDeptUserNodesStatus(deptNode, selectedIds) {
  const userNodes = getAllUserNodes(deptNode);
  const selectedUserNodes = userNodes.filter(id => selectedIds.includes(id));
  return {
    userNodes,
    isAllSelected: selectedUserNodes.length === userNodes.length && userNodes.length > 0
  };
}

// 树形选择器变更事件
function handleTreeSelectChange(value) {
  const lastSelected = value[value.length - 1];
  if (lastSelected) {
    const node = findNodeById(userList.value, lastSelected);
    if (node && node.type === 'dept') {
      const { userNodes, isAllSelected } = checkDeptUserNodesStatus(node, selectedUsers.value);
      if (isAllSelected) {
        // 如果部门下所有用户节点已选中，则取消选中
        selectedUsers.value = selectedUsers.value.filter(id => 
          !userNodes.includes(id) && id !== lastSelected
        );
      } else {
        // 如果部门下存在未选中的用户节点，则全选
        selectedUsers.value = Array.from(new Set([...selectedUsers.value.filter(id => id !== lastSelected), ...userNodes]));
      }
    } else {
      selectedUsers.value = value;
    }
  } else {
    selectedUsers.value = value;
  }
}

// 确认按钮事件
function handleConfirm() {
  if (selectedUsers.value.length === 0) {
    proxy.$modal.msgError('请选择用户');
    return;
  }
  emit('confirm', {
    users: selectedUsers.value,
    priority: priority.value
  });
}

// 取消按钮事件
function handleCancel() {
  selectedUsers.value = [];
  emit('cancel');
}

onMounted(() => {
  getUsers();
  getPriorityOptions();
});

onBeforeUnmount(() => {
  selectedUsers.value = [];
  priority.value = '';
});
</script>

<style lang="scss" scoped>
.user-select {
  padding: 20px;
  .priority-select {
    margin-top: 10px;
    width: 100%;
  }
  .dialog-footer {
    margin-top: 20px;
    text-align: center;
  }
}
</style>